package com.py.framework.controller;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.framework.common.Constants;
import com.py.framework.common.controller.SystemController;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.core.utils.DateUtils;
import com.py.framework.entity.AreaEntity;
import com.py.framework.entity.OfficeEntity;
import com.py.framework.entity.UserEntity;
import com.py.framework.service.AreaService;
import com.py.framework.service.AuthenticationService;
import com.py.framework.service.OfficeService;
import com.py.framework.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 用户管理Controller
 * @author Leegern
 * @date   2018年4月25日
 */
@Api(tags = "user", description = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController extends SystemController {

	public static final String PERMISSION_DENIED = "你无此权限，不能使用此功能，请联系管理员";

	@Autowired
	private UserService userService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private AuthenticationService authenticationService;
	
	/**
	 * @api {post} /user/addUserInfo.json 添加用户实体
	 * @apiName addUserInfo
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {UserEntity}  entity 用户实体
	 * @apiParam {String} username 用户名
	 * @apiParam {String} password 密码
	 * @apiParam {String} realName  真实姓名 
	 * @apiParam {String} mobilePhone  手机号 
	 * @apiParam {long} officeId 部门ID
	 * @apiParam {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员 4：部门管理员
	 * @apiParam {int} userStatus 用户状态，1：启用，2：停用
	 * @apiParamExample {json} 请求参数示例
	 *  {"username":"bdmin","password":"111111","realName":"信息中信","mobilePhone":"13182853599","officeId":2,"userType":2,"userStatus":1}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/addUserInfo", method = RequestMethod.POST)
	@ApiOperation(value = "添加用户", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "body", dataType = "UserEntity", name = "entity", value = "用户信息实体", required = true) })
	public RestServiceResult<Object> addUserInfo(@RequestBody UserEntity entity, HttpServletRequest request) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				// 获取当前用户信息
				UserEntity user = authenticationService.getCurrentUserInfo(HttpServletHelper.getUserToken(request));
				if (null != user && user.getId() > Constants.NUMBER_ZERO) {
					int userType = user.getUserType();
					if (1 == userType) {
						// 普通用户无法创建用户
						return super.getFailedRestServiceResult(PERMISSION_DENIED);
					} else if (4 == userType) {
						Map<String, Object> params = new HashMap<>(2);
						params.put("officeId", entity.getOfficeId());
						// 部门管理员用户
						params.put("userOfficeId", user.getOfficeId());
						int num = officeService.checkAddPermission(params);
						// 部门管理员能创建普通员工
						if (num <= 0 || 1 != entity.getUserType()) {
							return super.getFailedRestServiceResult(PERMISSION_DENIED);
						}
					} else if (2 == userType) {
						Map<String, Object> params = new HashMap<>(2);
						params.put("officeId", entity.getOfficeId());
						// 区域管理员用户
						params.put("userAreaId", user.getAreaId());
						int num = officeService.checkAddPermission(params);
						// 区域管理员能创建部门管理员、普通员工
						if (num <= 0 || 2 == entity.getUserType() || 3 == entity.getUserType()
								|| 5 == entity.getUserType()) {
							return super.getFailedRestServiceResult(PERMISSION_DENIED);
						}
					}
				}
				this.setTimes(entity);
				userService.addUserInfo(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("添加失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /user/queryUsersForPage.json 分页查询用户列表
	 * @apiName queryUsersForPage
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {int}  page  当前页码
	 * @apiParam {int}  limit 每页条数
	 * @apiParam {String}  realName 真实姓名
	 * @apiParam {String}  mobilePhone 手机号
	 * @apiParam {long}  areaId 区域Id
	 * @apiParam {long}  officeId 部门Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 用户Id
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} password 密码
	 * @apiSuccess {String} realName  真实姓名 
	 * @apiSuccess {String} mobilePhone  手机号 
	 * @apiSuccess {long} officeId 部门ID
	 * @apiSuccess {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员
	 * @apiSuccess {int} userStatus 用户状态，1：启用，2：停用
	 * @apiSuccess {long} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data":[{"id":2,"createTime":1531362480000,"username":"bdmin","password":"111111","realName":"信息中信","mobilePhone":"13182853599","officeId":2,"userType":2,"userStatus":1,"officeName":"信息中信","areaName":"建邺区"}]}
	 */
	@RequestMapping(value = "/queryUsersForPage", method = RequestMethod.POST)
	@ApiOperation(value = "分页查询用户列表", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "int", name = "page", value = "页码", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "int", name = "limit", value = "分页大小", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "realName", value = "真实姓名", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "mobilePhone", value = "手机号", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "areaId", value = "区域ID", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "officeId", value = "部门ID", required = true) })
	public RestServiceResult<List<UserEntity>> queryUsersForPage(HttpServletRequest request,int page, int limit, String realName, String mobilePhone, 
																 String areaId, String officeId) {
		Map<String, Object> params = new HashMap<>();
		Page pager = super.getPage(page, limit);
		long userId = super.pickUserId(request);
		params.put("page", pager);
		params.put("realName", realName);
		params.put("mobilePhone", mobilePhone);
		params.put("areaId", areaId);
		params.put("officeId", officeId);
		params.put("userId", userId);
		String jdToken = HttpServletHelper.getUserToken(request);
		try {
			// 获取当前用户信息
			UserEntity user = authenticationService.getCurrentUserInfo(jdToken);
//			if (null != user && user.getId() > Constants.NUMBER_ZERO) {
//				int userType = user.getUserType();
//				params.put("userType", userType);
//				params.put("userOfficeId", user.getOfficeId());
//				params.put("userAreaId", user.getAreaId());
//			}
			if(!user.getRoleName().equals("系统管理员")) {
				return super.getPageSuccessRestServiceResult(pager.getTotalCount(), Collections.emptyList());
			}
		} catch (Exception e) {
			ExceptionLogger.error("UserController#queryUsersForPage", "获取当前用户数据异常", e);
			return super.getPageSuccessRestServiceResult(pager.getTotalCount(), Collections.emptyList());
		}
		List<UserEntity> datas = userService.queryUsersForPage(params);
		return super.getPageSuccessRestServiceResult(pager.getTotalCount(), datas);
	}
	
	/**
	 * @api {post} /user/findOneUser.json 根据部门Id获取用户信息
	 * @apiName findOneUser
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {long}  id 部门Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 用户Id
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} password 密码
	 * @apiSuccess {String} realName  真实姓名 
	 * @apiSuccess {String} mobilePhone  手机号 
	 * @apiSuccess {long} officeId 部门ID
	 * @apiSuccess {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员
	 * @apiSuccess {int} userStatus 用户状态，1：启用，2：停用
	 * @apiSuccess {long} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data":{"id":2,"createTime":1531362480000,"username":"bdmin","password":"111111","realName":"信息中信","mobilePhone":"13182853599","officeId":2,"userType":2,"userStatus":1,"officeName":"信息中信","areaName":"建邺区"}}
	 */
	@RequestMapping(value = "/findOneUser", method = RequestMethod.POST)
	@ApiOperation(value = "根据部门Id获取用户信息", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "id", value = "用户ID", required = true) })
	public RestServiceResult<UserEntity> findOneUser(long id) {
		UserEntity data = null;
		if (id > Constants.NUMBER_ZERO) {
			data = userService.findOneUser(id);
		}
		return super.getSuccessRestServiceResult(data);
	}
	
	/**
	 * @api {post} /user/getAllAreas.json 查询所有区域数据
	 * @apiName getAllAreas
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} areaCode 区域编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} parentAreaName 父节点名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data": [{"id":1,"createTime":1525244806000,
	 *    "areaName":"江苏省","areaCode":"32000","parentId":0,"allParentId":"","orderBy":1}]}
	 */
	@RequestMapping(value = "/getAllAreas", method = RequestMethod.POST)
	@ApiOperation(value = "查询所有区域数据", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<List<AreaEntity>> getAllAreas() {
		List<AreaEntity> datas = areaService.getAllAreas();
		return super.getSuccessRestServiceResult(datas);
	}
	
	/**
	 * @api {post} /user/getAllOffices.json 根据所有部门数据
	 * @apiName getAllOffices
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":3,"data":[{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}]}
	 */
	@RequestMapping(value = "/getAllOffices", method = RequestMethod.POST)
	@ApiOperation(value = "查询所有部门数据", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<List<OfficeEntity>> getAllOffices() {
		List<OfficeEntity> datas = officeService.getOfficesByOfficeId(null);
		return super.getSuccessRestServiceResult(datas);
	}
	
	/**
	 * @api {get} /user/getSubOfficesByAreaId.json 根据区域Id获取部门以及子部门数据
	 * @apiName getSubOfficesByAreaId
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {long}  areaId 区域Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} officeName 部门名称
	 * @apiSuccess {String} officeCode 部门编码
	 * @apiSuccess {long} parentId 父节点ID
	 * @apiSuccess {long} areaId 区域ID
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {String} areaName 区域名称
	 * @apiSuccess {String} parentOfficeName 父部门名称
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":3,"data":[{"id":1,"createTime":1531303130000,"updateTime":1531303130000,"delFlag":1,"officeName":"工商局","officeCode":"gsj","parentId":0,"areaId":2,"orderBy":1,"areaName":"建邺区","parentOfficeName":null}]}
	 */
	@RequestMapping(value = "/getSubOfficesByAreaId", method = RequestMethod.POST)
	@ApiOperation(value = "根据区域Id获取部门以及子部门数据", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "areaId", value = "区域ID", required = true) })
	public RestServiceResult<List<OfficeEntity>> getSubOfficesByAreaId(long areaId) {
		List<OfficeEntity> datas = null;
		if (areaId > Constants.NUMBER_ZERO) {
			datas = officeService.getSubOfficesByAreaId(areaId);
		}
		return super.getSuccessRestServiceResult(datas);
	}
	
	
	/**
	 * @api {post} /user/updateUserInfo.json 更新用户信息
	 * @apiName updateUserInfo
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {UserEntity}  entity 用户实体
	 * @apiParam {long} id 用户Id
	 * @apiParam {String} username 用户名
	 * @apiParam {String} password 密码
	 * @apiParam {String} realName  真实姓名 
	 * @apiParam {String} mobilePhone  手机号 
	 * @apiParam {long} officeId 部门ID
	 * @apiParam {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员
	 * @apiParam {int} userStatus 用户状态，1：启用，2：停用
	 * @apiParamExample {json} 请求参数示例
	 *  {"id":99, "username":"bdmin","password":"111111","realName":"信息中信","mobilePhone":"13182853599","officeId":2,"userType":2,"userStatus":1}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
	@ApiOperation(value = "更新用户信息", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "body", dataType = "UserEntity", name = "entity", value = "用户实体", required = true) })
	public RestServiceResult<Object> updateUserInfo(@RequestBody UserEntity entity, HttpServletRequest request) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (null != entity) {
			try {
				// 获取当前用户信息
				UserEntity user = authenticationService.getCurrentUserInfo(HttpServletHelper.getUserToken(request));
				if (null != user && user.getId() > Constants.NUMBER_ZERO) {
					UserEntity orgUser = userService.findOneUser(entity.getId());
					int userType = user.getUserType();
					if (1 == userType) {
						// 普通用户无法修改用户
						return super.getFailedRestServiceResult(PERMISSION_DENIED);
					} else if (4 == userType) {
						Map<String, Object> params = new HashMap<>(2);
						params.put("officeId", entity.getOfficeId());
						// 部门管理员用户
						params.put("userOfficeId", user.getOfficeId());
						int num = officeService.checkAddPermission(params);
						// 部门管理员能修改普通员工
						if (num <= 0 || 1 != orgUser.getUserType() || 1 != entity.getUserType()) {
							return super.getFailedRestServiceResult(PERMISSION_DENIED);
						}
					} else if (2 == userType) {
						Map<String, Object> params = new HashMap<>(2);
						params.put("officeId", entity.getOfficeId());
						// 区域管理员用户
						params.put("userAreaId", user.getAreaId());
						int num = officeService.checkAddPermission(params);
						// 区域管理员能修改部门管理员、普通员工
						if (num <= 0 || 2 == entity.getUserType() || 5 == entity.getUserType()
								|| 2 == orgUser.getUserType() || 5 == orgUser.getUserType()) {
							return super.getFailedRestServiceResult(PERMISSION_DENIED);
						}
					}
				}
				this.setTimes(entity);
				entity.setPassword(null);
				userService.updateUserInfo(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /user/resetPassword.json 重置密码
	 * @apiName resetPassword
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {long}  userId 用户ID
	 * @apiParam {String}  newPassword 新密码
	 * @apiParam {String}  newPassword2 新密码2
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
	@ApiOperation(value = "重置密码", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "userId", value = "用户ID", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "newPassword", value = "新密码", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "newPassword2", value = "新密码2", required = true) })
	public RestServiceResult<Object> resetPassword(long userId, String newPassword, String newPassword2,
			HttpServletRequest request) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(newPassword2) &&
			userId > Constants.NUMBER_ZERO && newPassword.equals(newPassword2)) {
			try {
				UserEntity user = userService.findOneUser(userId);
				if (null == user) {
					result = super.getFailedRestServiceResult("用户不存在！");
				}
				// 获取当前用户信息
				UserEntity currUser = authenticationService.getCurrentUserInfo(HttpServletHelper.getUserToken(request));
				if (null != currUser && currUser.getId() > Constants.NUMBER_ZERO) {
					int userType = currUser.getUserType();
					if (1 == userType) {
						// 普通用户无法修改用户
						return super.getFailedRestServiceResult(PERMISSION_DENIED);
					} else if (4 == userType) {
						Map<String, Object> params = new HashMap<>(2);
						params.put("officeId", user.getOfficeId());
						// 部门管理员用户
						params.put("userOfficeId", currUser.getOfficeId());
						int num = officeService.checkAddPermission(params);
						// 部门管理员能修改普通员工
						if (num <= 0 || 1 != user.getUserType()) {
							return super.getFailedRestServiceResult(PERMISSION_DENIED);
						}
					} else if (2 == userType) {
						Map<String, Object> params = new HashMap<>(2);
						params.put("officeId", user.getOfficeId());
						// 区域管理员用户
						params.put("userAreaId", currUser.getAreaId());
						int num = officeService.checkAddPermission(params);
						// 区域管理员能修改部门管理员、普通员工
						if (num <= 0 || 2 == user.getUserType() || 3 == user.getUserType() || 5 == user.getUserType()) {
							return super.getFailedRestServiceResult(PERMISSION_DENIED);
						}
					}
				}
				UserEntity entity = new UserEntity();
				entity.setId(userId);
				entity.setPassword(newPassword);
				entity.setUpdateTime(new Timestamp(DateUtils.getCurrentDateTime().getTime()));
				userService.updateUserInfo(entity);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("更新失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /user/updatePassword.json 修改密码
	 * @apiName updatePassword
	 * @apiVersion 0.0.1
	 * @apiGroup 用户密码修改 
	 * @apiParam {long}  userId 用户ID
	 * @apiParam {String}  oldPassword 旧密码
	 * @apiParam {String}  newPassword 新密码
	 * @apiParam {String}  newPassword2 新密码2
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	@ApiOperation(value = "修改密码", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "userId", value = "用户ID", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "oldPassword", value = "旧密码", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "newPassword", value = "新密码", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "newPassword2", value = "新密码2", required = true) })
	public RestServiceResult<Object> updatePassword(long userId, String oldPassword, String newPassword,
			String newPassword2) {
		RestServiceResult<Object> result =null;
		if(StringUtils.isBlank(oldPassword)) {
			result=super.getFailedRestServiceResult("原密码不能为空！");
		}else {
			UserEntity user = userService.findOneUser(userId);
			if(null==user) {
				result = super.getFailedRestServiceResult("用户不存在！");
			}else {
				if(! oldPassword.equals(user.getPassword())) {
					result = super.getFailedRestServiceResult("原密码填写错误！");
				}else {
					if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(newPassword2) &&
							userId > Constants.NUMBER_ZERO && newPassword.equals(newPassword2)) {
							try {
								UserEntity entity = new UserEntity();
								entity.setId(userId);
								entity.setPassword(newPassword);
								entity.setUpdateTime(new Timestamp(DateUtils.getCurrentDateTime().getTime()));
								userService.updateUserInfo(entity);
								result =super.getSuccessRestServiceResult();
							} catch (Exception e) {
								result = super.getFailedRestServiceResult("更新失败！");
								ExceptionLogger.error(e);
							}
						}else {
							result = super.getFailedRestServiceResult("新密码有误！");
						}
				}
			}
		}	
		return result;
	}
	/**
	 * @api {post} /user/batchDelUsers.json 批量删除用户
	 * @apiName batchDelUsers
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {String}  ids 部门Id集合
	 * @apiParam {HttpServletRequest}  request 请求对象
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":null}
	 */
	@RequestMapping(value = "/batchDelUsers", method = RequestMethod.POST)
	@ApiOperation(value = "批量删除用户", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "ids", value = "部门Id集合", required = true) })
	public RestServiceResult<Object> batchDelUsers(String ids, HttpServletRequest request) {
		RestServiceResult<Object> result = super.getSuccessRestServiceResult();
		if (StringUtils.isNotBlank(ids)) {
			try {
				UserEntity currUser = authenticationService.getCurrentUserInfo(HttpServletHelper.getUserToken(request));
				if (null == currUser || currUser.getId() <= 0) {
					super.getFailedRestServiceResult("未获取当前用户，请重新登录");
				} else {
					List<Long> delUserIds = super.convert2Long(ids);
					List<Long> userIds = userService.getDealUser(currUser);
					delUserIds.retainAll(userIds);
					if (!CollectionUtils.isEmpty(delUserIds)) {
						userService.batchDelUsers(delUserIds, super.pickUserId(request));
					} else {
						result = super.getFailedRestServiceResult(PERMISSION_DENIED);
					}
				}
			} catch (ServiceException e) {
				result = super.getFailedRestServiceResult(e.getMessage());
				ExceptionLogger.error(e);
			} catch (Exception e) {
				result = super.getFailedRestServiceResult("删除失败！");
				ExceptionLogger.error(e);
			}
		}
		return result;
	}
	
	/**
	 * @api {post} /user/getUsersByName.json 根据姓名查询用户信息
	 * @apiName getUsersByName
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {String}  realName 用户姓名
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {long} id 用户Id
	 * @apiSuccess {String} username 用户名
	 * @apiSuccess {String} password 密码
	 * @apiSuccess {String} realName  真实姓名 
	 * @apiSuccess {String} mobilePhone  手机号 
	 * @apiSuccess {long} officeId 部门ID
	 * @apiSuccess {int} userType 用户类型，1：普通用户，2：区域管理员，3：超级管理员
	 * @apiSuccess {int} userStatus 用户状态，1：启用，2：停用
	 * @apiSuccess {long} createTime 创建时间
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":"","count":1,"data":[{"id":2,"createTime":1531362480000,"username":"bdmin","password":"111111","realName":"信息中信","mobilePhone":"13182853599","officeId":2,"userType":2,"userStatus":1,"officeName":"信息中信","areaName":"建邺区"}]}
	 */
	@RequestMapping(value = "/getUsersByName", method = RequestMethod.POST)
	@ApiOperation(value = "根据姓名查询用户信息", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "realName", value = "用户姓名", required = true) })
	public RestServiceResult<List<UserEntity>> getUsersByName(String realName) {
		List<UserEntity> users = null;
		if (StringUtils.isNotBlank(realName)) {
			users = userService.getUsersByName(realName);
		}
		return super.getSuccessRestServiceResult(users);
	}
	
	/**
	 * @api {post} /user/isExistUser.json 根据用户名判断是否有重复数据
	 * @apiName isExistUser
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {String}  username 用户名
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} flag true 存在重复, false 不存在重复
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":{"flag":"true"}}
	 */
	@RequestMapping(value = "/isExistUser", method = RequestMethod.POST)
	@ApiOperation(value = "根据用户名判断是否有重复数据", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "username", value = "用户名", required = true) })
	public RestServiceResult<Map<String, String>> isExistUser(String username) {
		RestServiceResult<Map<String, String>> rstData = null;
		Map<String, String> result = new HashMap<>();
		String flag = "";
		if (StringUtils.isNotBlank(username)) {
			try {
				UserEntity datas = userService.getUserByPrincipal(username);
				if (null!=datas) {
					
					if(datas.getDelFlag()==1) {
						flag = "Tture1";
					}else {
						flag = "Tture2";	
					}
					
				} else {
					flag = "false";
				}
				result.put("flag", flag);
			} catch (Exception e) {
				rstData = super.getFailedRestServiceResult("查询失败！");
				ExceptionLogger.error(e);
			}
		}
		rstData = super.getSuccessRestServiceResult(result);
		return rstData;
	}
	
	/**
	 * @api {post} /user/isExistAreaAdmin.json 判断同区域是否有重复管理员
	 * @apiName isExistAreaAdmin
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理 
	 * @apiParam {long}  officeId 部门Id
	 * @apiParam {long}  userId 用户Id
	 * @apiParamExample {json} 请求参数示例
	 *  {}
	 * @apiSuccess {String} code 状态码:0 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} flag true 存在重复, false 不存在重复
	 * @apiSuccessExample {json} 成功返回结果
	 *   {"code":0,"msg":null,"count":0,"data":{"flag":"true"}}
	 */
	@RequestMapping(value = "/isExistAreaAdmin", method = RequestMethod.POST)
	@ApiOperation(value = "判断同区域是否有重复管理员", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "officeId", value = "部门Id", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "userId", value = "用户Id", required = true) })
	public RestServiceResult<Map<String, String>> isExistAreaAdmin(long officeId, 
			@RequestParam(value="userId", required=false, defaultValue="0") long userId) {
		RestServiceResult<Map<String, String>> rstData = null;
		Map<String, String> result = new HashMap<>();
		String flag = "";
		if (officeId > Constants.NUMBER_ZERO) {
			try {
				List<UserEntity> datas = userService.getAreaAdminUsers(userId, officeId);
				if (! CollectionUtils.isEmpty(datas)) {
					flag = "true";
				} else {
					flag = "false";
				}
				result.put("flag", flag);
			} catch (Exception e) {
				rstData = super.getFailedRestServiceResult("查询失败！");
				ExceptionLogger.error(e);
			}
		}
		rstData = super.getSuccessRestServiceResult(result);
		return rstData;
	}
	
	/**
	 * 
	 * @api {get} /user/isExistDeptAdmin.json 判断部门是否有重复部门管理员
	 * @apiName getDeptAdminUsers
	 * @apiVersion 0.0.1
	 * @apiGroup 用户管理
	 * @apiParam {long} officeId 部门ID
	 * @apiParam {long} userId 用户ID
	 * @apiParamExample {json} 请求参数示例
	 *                  {"officeId":1,"userId":2}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object} data 结果集
	 * @apiSuccess {String} flag true 存在重复, false 不存在重复
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":{"flag":"true"}}
	 */
	@RequestMapping(value = "/isExistDeptAdmin", method = RequestMethod.POST)
	@ApiOperation(value = "判断部门是否有重复部门管理员", httpMethod = "POST", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "officeId", value = "部门Id", required = true),
			@ApiImplicitParam(paramType = "query", dataType = "long", name = "userId", value = "用户Id", required = true) })
	public RestServiceResult<Map<String, String>> getDeptAdminUsers(long officeId,
			@RequestParam(value = "userId", required = false, defaultValue = "0") long userId) {
		RestServiceResult<Map<String, String>> rstData = null;
		Map<String, String> result = new HashMap<>();
		String flag = "";
		if (officeId > Constants.NUMBER_ZERO) {
			try {
				List<UserEntity> datas = userService.getDeptAdminUsers(userId, officeId);
				if (!CollectionUtils.isEmpty(datas)) {
					flag = "true";
				} else {
					flag = "false";
				}
				result.put("flag", flag);
			} catch (Exception e) {
				rstData = super.getFailedRestServiceResult("查询失败！");
				ExceptionLogger.error(e);
			}
		}
		rstData = super.getSuccessRestServiceResult(result);
		return rstData;
	}

	/**
	 * 设置当前时间
	 * @param entity
	 */
	private void setTimes(UserEntity entity) {
		Timestamp currentTime = new Timestamp(DateUtils.getCurrentDateTime().getTime());
		entity.setCreateTime(currentTime);
		entity.setUpdateTime(currentTime);
	}
	/**
	 * 获取角色
	 * @return
	 */
	@RequestMapping(value = "/findUserRole", method = RequestMethod.POST)
	@ApiOperation(value = "获取所有角色信息", httpMethod = "POST", produces = "application/json")
	public RestServiceResult<List<String>> findUserRole() {
		
		
		List<String> data = userService.findUserRole();
		
		return super.getSuccessRestServiceResult(data);
	}
}